package com.ssmsq.multidatabase.service;

import com.ssmsq.multidatabase.entity.AlbbSms;
import com.ssmsq.multidatabase.repository.AlbbSmsRepository;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author sss
 */
@Service
public class SsmService {

    @Resource
    private SysUserService sysUserService;

    @Resource
    private AlbbSmsRepository albbSmsRepository;

    @Resource
    private RedisService redisService;

    public boolean testRoll(Integer a, Integer b) {
        boolean flag = false;
        try {
            flag = sysUserService.testRoll(a, b);
        } catch (Exception e) {
            System.out.println("异常就不抛前端了");
        }
        return flag;
    }

    public Object mongoSave(Integer a, Integer b) {
        AlbbSms albbSms = new AlbbSms();
        LocalDateTime now = LocalDateTime.now();
        long timestamp = now.toEpochSecond(ZoneOffset.of("+8"));
        String phone = "13888888888";
        if(a != null) {
            phone = a + "";
        }
        String mode = "1";
        if(b != null) {
            mode = b + "";
        }
        albbSms.setPhoneNumber(phone);
        albbSms.setClientId(timestamp + "");
        albbSms.setModeType(mode);
        albbSms.setTime(now);
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "success");
        albbSms.setResponseData(response);
        Map<String, String> params = new HashMap<>();
        params.put("a", "1");
        albbSms.setRequestParams(params);
        AlbbSms save = albbSmsRepository.save(albbSms);
        return save;
    }

    public Object mongoGet(Integer a, Integer b) {
        String phone = "13888888888";
        if(a != null) {
            phone = a + "";
        }
        String mode = "1";
        if(b != null) {
            mode = b + "";
        }
        List<AlbbSms> byPhoneNumber = albbSmsRepository.findByPhoneNumberAndModeType(phone, mode);
        return byPhoneNumber;
    }

    public Object redisSave(Integer a, Integer b) {
        String key = "token";
        if(a != null) {
            key = a + "";
        }
        String value = "13888888888";
        if(b != null) {
            value = b + "";
        }
        redisService.setCacheObject(key, value, 300L, TimeUnit.SECONDS);
        return true;
    }

    public Object redisGet(Integer a, Integer b) {
        String key = "token";
        if(a != null) {
            key = a + "";
        }
        Object cacheObject = redisService.getCacheObject(key);
        return cacheObject;
    }

}
